package controller

import (
	"../tools"
	"encoding/json"
	"github.com/Unknwon/com"
	"net/http"
	"strings"
)
func init() {

	/**
	  根目录的默认访问，指向默认的README文件
	 */
	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		writer.Write(tools.CreateHtml("md/index.txt"))
	})

	/**
		file开头的请求，主要是访问指定的文件
	 */
	http.HandleFunc("/file/", func(writer http.ResponseWriter, request *http.Request) {
		filePath := strings.Replace(request.RequestURI,"/file/","",1)
		decode, _ := com.UrlDecode(filePath)
		decode ,_ =com.UrlDecode(decode)
		writer.Write(tools.CreateHtml(decode))
	})

	/**
		访问指定目录当前一层的文件和目录
	 */
	http.HandleFunc("/dir/", func(writer http.ResponseWriter, request *http.Request) {
		filePath := strings.Replace(request.RequestURI,"/dir/","",1)
		dir := tools.ReadDir(tools.PathFormat(filePath))
		marshal, _ := json.Marshal(dir)
		writer.Header().Add("Content-Type","application/json")
		writer.Write(marshal)
	})
	/**
		访问指定目录的所有子目录和文件
	 */
	http.HandleFunc("/dir/all", func(writer http.ResponseWriter, request *http.Request) {
		filePath:="md"
		dir := tools.ReadDirAll(tools.PathFormat(filePath))
		marshal, _ := json.Marshal(dir)

		writer.Header().Add("Content-Type","application/json")
		writer.Write(marshal)
	})
}


